package com.dlut.service.impl;

import com.dlut.mapper.BasicDataMapper;
import com.dlut.pojo.BasicData;
import com.dlut.pojo.BasicDataExample;
import com.dlut.service.IBasicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BasicDataServiceImpl implements IBasicService {

    @Autowired
    private BasicDataMapper mapper;

    @Override
    public List<BasicData> query(BasicData basicData) throws Exception {
        BasicDataExample example = new BasicDataExample();
        return mapper.selectByExample(example);
    }

    @Override
    public BasicData queryById(Integer id) throws Exception {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer addBasicData(BasicData basicData) throws Exception {
        if (basicData.getParentId() != null && basicData.getParentId() == -1){
            //parent为空，为大类
            basicData.setParentId(null);
        }
        return mapper.insertSelective(basicData);
    }

    @Override
    public Integer updateBasicData(BasicData basicData) throws Exception {
        if (basicData.getParentId()!=null && basicData.getParentId()== -1){
            basicData.setParentId(null);
        }
        return mapper.updateByPrimaryKeySelective(basicData);
    }

    @Override
    public Integer deleteBasicData(Integer id) throws Exception {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<BasicData> queryAllParentData() throws Exception {
        BasicDataExample example = new BasicDataExample();
        example.createCriteria().andParentIdIsNull();
        return mapper.selectByExample(example);
    }

    //根据父类名称查询
    @Override
    public List<BasicData> queryByParentName(String parentName) throws Exception {
        BasicDataExample example = new BasicDataExample();
        example.createCriteria().andBaseNameEqualTo(parentName);
        List<BasicData> parentData = mapper.selectByExample(example);
        if (parentData!=null && parentData.size()>0){
            BasicData data = parentData.get(0);
            BasicDataExample example1 = new BasicDataExample();
            example1.createCriteria().andParentIdEqualTo(data.getBaseId());
            List<BasicData> basicData = mapper.selectByExample(example1);
            return basicData;
        }
        return null;
    }
}
